package com.hyj.springai.repository;

import com.hyj.springai.utils.OssUtils;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.Properties;

@Slf4j
@Component
@RequiredArgsConstructor
public class LocalPdfFileRepository implements FileRepository {

    private final VectorStore vectorStore;

    private final OssUtils ossUtils;

    // 会话id 与 文件名的对应关系，方便查询会话历史时重新加载文件
    private final Properties chatFiles = new Properties();

    String json = "chat-pdf.json";
    String property = "chat-pdf.properties";

    @Override
    public int save(String chatId, Resource resource) {

        // 保存到OSS
        String filename = resource.getFilename();
        if (filename == null) {
            return 2;
        }
        try (InputStream inputStream = resource.getInputStream()) {
            int upload = ossUtils.upload(filename, inputStream);
            if (upload ==2) {
                return 2;
            }
            chatFiles.put(chatId, filename);
            return upload;
        } catch (IOException e) {
            log.error("保存 PDF 到 OSS 失败", e);
            return 2;
        }
    }

    @Override
    public Resource getFile(String chatId) {
        String filename = chatFiles.getProperty(chatId);
        return filename == null ? null : ossUtils.download(filename);
    }

    @PostConstruct
    private void init() {
        if (ossUtils.exists(property)) {
            try {
                chatFiles.load(new BufferedReader(new InputStreamReader(ossUtils.getInputStream(property), StandardCharsets.UTF_8)));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        if (ossUtils.exists(json)) {
            try {
                File temp = File.createTempFile("vector-store", ".json");
                try(OutputStream out = new FileOutputStream(temp)) {
                    ossUtils.getInputStream(json).transferTo(out);
                }
                SimpleVectorStore simpleVectorStore = (SimpleVectorStore) vectorStore;
                simpleVectorStore.load(temp);
                temp.deleteOnExit();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @PreDestroy
    private void persistent() {
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            chatFiles.store(new OutputStreamWriter(out, StandardCharsets.UTF_8), LocalDateTime.now().toString());
            ossUtils.upload(property, new ByteArrayInputStream(out.toByteArray()));
            File temp = File.createTempFile("vector-store", ".json");
            ((SimpleVectorStore) vectorStore).save(temp);
            ossUtils.upload(json, temp);
            temp.deleteOnExit();
        } catch (IOException e) {
            throw new RuntimeException("持久化保存到 OSS 失败", e);
        }
    }
}